package top.hmtools.mapper.plus.mysql;

import java.util.Set;

import org.apache.ibatis.mapping.MappedStatement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import tk.mybatis.mapper.entity.EntityColumn;
import tk.mybatis.mapper.mapperhelper.EntityHelper;
import tk.mybatis.mapper.mapperhelper.MapperHelper;
import tk.mybatis.mapper.mapperhelper.MapperTemplate;
import tk.mybatis.mapper.mapperhelper.SqlHelper;

/**
 * 通用mapper扩展方法具体实现
 * <br>增
 * @author Hybomyth
 *
 */
public class InsertMapperPlusProvider extends MapperTemplate{
	
	private final Logger logger = LoggerFactory.getLogger(InsertMapperPlusProvider.class);

	public InsertMapperPlusProvider(Class<?> mapperClass, MapperHelper mapperHelper) {
		super(mapperClass, mapperHelper);
	}

	/**
	 * 批量/单个 新增数据
	 * <br><b>注意：本方法不使用主键生成策略</b>
	 * @param ms
	 * @return
	 */
	public String addSome(MappedStatement ms){
		final Class<?> entityClass = getEntityClass(ms);
        //开始拼sql
        StringBuilder sql = new StringBuilder();
        sql.append(SqlHelper.insertIntoTable(entityClass, tableName(entityClass)));
        sql.append(SqlHelper.insertColumns(entityClass, false, false, false));
        sql.append(" VALUES ");
        sql.append("<foreach collection=\"ts\" item=\"record\" separator=\",\" >");
        sql.append("<trim prefix=\"(\" suffix=\")\" suffixOverrides=\",\">");
        //获取全部列
        Set<EntityColumn> columnList = EntityHelper.getColumns(entityClass);
        //当某个列有主键策略时，不需要考虑他的属性是否为空，因为如果为空，一定会根据主键策略给他生成一个值
        for (EntityColumn column : columnList) {
            sql.append(column.getColumnHolder("record") + ",");
        }
        sql.append("</trim>");
        sql.append("</foreach>");
        if(this.logger.isDebugEnabled()){
			this.logger.debug(Thread.currentThread().getStackTrace()[1].getMethodName()+"  :  "+sql.toString());
		}
        return sql.toString();
	}
	
	/**
	 * 批量/单个 忽略式新增数据
	 * <br><b>注意：本方法不使用主键生成策略</b>
	 * <br>当数据库表中存在相同主键的数据时，则忽略该条记录，继续写入其它记录
	 * @param ms
	 * @return
	 */
	public String addSomeIgnore(MappedStatement ms){
		String sql = "insert ignore "+this.addSome(ms).trim().substring("insert".length());
		if(this.logger.isDebugEnabled()){
			this.logger.debug(Thread.currentThread().getStackTrace()[1].getMethodName()+"  :  "+sql.toString());
		}
        return sql.toString(); 
	}
}
